package com.yisu.expressway.onedollar.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.yisu.expressway.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

/**
 * Created by haha on 16/2/22.
 */
public class ODIndexSlideShowView extends FrameLayout {

    //轮播图图片数量
    private final static int IMAGE_COUNT = 5;
    //自动轮播的时间间隔
    private final static int TIME_INTERVAL = 5;
    //自动轮播启用开关
    private final static boolean isAutoPlay = true;

    //自定义轮播图的资源
    private List mDataList;
    //放轮播图片的ImageView 的list
    private List<ImageView> imageViewsList;

    private ViewPager viewPager;
    //当前轮播页
    private int currentItem = 0;
    //定时任务
    private ScheduledExecutorService scheduledExecutorService;

    private TextView tvIndex;

    private Handler handler = new Handler();

    public ODIndexSlideShowView(Context context) {
        this(context, null);
    }

    public ODIndexSlideShowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ODIndexSlideShowView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidht, scaleHeight, x, y;
        Bitmap newbmp;
        Matrix matrix = new Matrix();
        if (width > height) {
            scaleWidht = ((float) h / height);
            scaleHeight = ((float) h / height);
            int i = (width - w * height / h) / 2;
            x = i < 0 ? 0 : i;
            y = 0;
        } else if (width < height) {
            scaleWidht = ((float) w / width);
            scaleHeight = ((float) w / width);
            x = 0;
            int i = (height - h * width / w) / 2;
            y = i < 0 ? 0 : i;// 获取bitmap源文件中y做表需要偏移的像数大小
        } else {
            scaleWidht = ((float) w / width);
            scaleHeight = ((float) w / width);
            x = 0;
            y = 0;
        }
        matrix.postScale(scaleWidht, scaleHeight);
        try {
            newbmp = Bitmap.createBitmap(bitmap, (int) x, (int) y, (int) (width - x),
                    (int) (height - y), matrix, true);// createBitmap()方法中定义的参数x+width要小于或等于bitmap.getWidth()，y+height要小于或等于bitmap.getHeight()
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return newbmp;
    }

    /**
     * 开始轮播图切换
     */
    public void startPlay() {
        handler.removeCallbacksAndMessages(null);
        handler.post(new SlideShowTask());
    }

    /**
     * 停止轮播图切换
     */
    public void stopPlay() {
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 初始化相关Data
     */
    public void initData(Context ctx, List configs) {
        imageViewsList = new ArrayList<ImageView>();
        mDataList = configs;
        if (isAutoPlay) {
            initUI(ctx);

            if (scheduledExecutorService != null) {
                scheduledExecutorService.shutdownNow();
                scheduledExecutorService = null;
            }
            //initImageLoader(ctx);
            if (mDataList != null && mDataList.size() > 1) {
                updateIndicator(0);
            }
            startPlay();

        }
    }

    /**
     * 初始化Views等UI
     */
    private void initUI(final Context context) {

        LayoutInflater.from(context).inflate(R.layout.layout_index_odslideshow, this, true);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        tvIndex = (TextView) findViewById(R.id.tv_index);
        if (mDataList == null || mDataList.size() == 0) {
            ImageView view = new ImageView(context);
            view.setScaleType(ScaleType.CENTER);
            view.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
            imageViewsList.add(view);
        } else {
            // 热点个数与图片特殊相等
            for (int i = 0; i < mDataList.size(); i++) {
                Object o = mDataList.get(i);
                if (o == null) {
                    break;
                }
                final ImageView view = new ImageView(context);
                if (o instanceof String) {
                    String item = (String) o;
                    if (!TextUtils.isEmpty(item)) {
                        view.setScaleType(ScaleType.FIT_XY);
                        Glide.with(getContext().getApplicationContext()).load(item)
                                .placeholder(R.drawable.blank)
                                .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop().into(view);
                        //
                        //                        WindowManager wm = (WindowManager) getContext()
                        //                                .getSystemService(Context.WINDOW_SERVICE);
                        //                        final int width = wm.getDefaultDisplay().getWidth();
                        //                        final int height = DensityUtil.dip2px(getContext(), 238);
                        //
                        //                        try {
                        //
                        //                            Glide.with(getContext().getApplicationContext()).load(item).asBitmap()
                        //                                    .placeholder(R.drawable.blank)
                        //                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                        //                                    .into(new SimpleTarget<Bitmap>(width, height) {
                        //
                        //                                        @Override
                        //                                        public void onResourceReady(Bitmap resource,
                        //                                                                    GlideAnimation<? super Bitmap> glideAnimation) {
                        //                                            PaletteTrigger paletteTrigger = new PaletteTrigger();
                        //                                            paletteTrigger.setBitmap(resource);
                        //                                            Prism.Builder.newInstance()
                        //                                                    .add(paletteTrigger)
                        //                                                    .background(view, paletteTrigger.getVibrantFilter(paletteTrigger.getBodyTextColour()))
                        //                                                    .add(new Setter() {
                        //	                                                    @Override
                        //	                                                    public void setColour(@ColorInt int colour) {
                        //
                        //	                                                    }
                        //
                        //	                                                    @Override
                        //	                                                    public void setTransientColour(@ColorInt int colour) {
                        //
                        //	                                                    }
                        //                                                    })
                        //	                                                .build();
                        //                                            view.setImageBitmap(resource);
                        //                                        }
                        //                                    });
                        //                        } catch (Exception e) {
                        //                            e.printStackTrace();
                        //                            view.setScaleType(ScaleType.CENTER);
                        //                            view.setImageDrawable(
                        //                                    getResources().getDrawable(R.drawable.pic_loading));
                        //                        }

                    } else {
                        view.setScaleType(ScaleType.CENTER);
                        view.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
                    }

                }

                imageViewsList.add(view);

            }
        }

        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());
        updateIndicator(0);
    }

    /**
     * 销毁ImageView资源，回收内存
     */
    private void destoryBitmaps() {

        for (int i = 0; i < IMAGE_COUNT; i++) {
            ImageView imageView = imageViewsList.get(i);
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                //解除drawable对view的引用
                drawable.setCallback(null);
            }
        }
    }

    private void updateIndicator(int currentPos) {
        if (tvIndex != null && mDataList != null && !mDataList.isEmpty()) {
            StringBuilder stringBuilder = new StringBuilder().append(currentPos + 1).append("/")
                    .append(mDataList.size());
            tvIndex.setText(stringBuilder.toString());
        }
    }

    /**
     * 填充ViewPager的页面适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViewsList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case ViewPager.SCROLL_STATE_DRAGGING:// 手势滑动，空闲中
                    isAutoPlay = false;
                    if (scheduledExecutorService != null
                            && !scheduledExecutorService.isShutdown()) {
                        scheduledExecutorService.shutdownNow();
                    }
                    scheduledExecutorService = null;
                    break;
                case ViewPager.SCROLL_STATE_SETTLING:// 界面切换中
                    isAutoPlay = true;
                    break;
                case ViewPager.SCROLL_STATE_IDLE:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1
                            && !isAutoPlay) {
                        viewPager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            currentItem = pos;
            updateIndicator(pos);
        }

    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {
        @Override
        public void run() {
            if (imageViewsList != null && !imageViewsList.isEmpty()) {
                currentItem = (currentItem + 1) % imageViewsList.size();
                viewPager.setCurrentItem(currentItem);
            }
            handler.postDelayed(this, 4000);
        }
    }
}
